//
//  DigitAlbumLargeImageViewController.m
//  NewApp
//
//  Created by xueyan liu on 7/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DigitAlbumLargeImageViewController.h"
#import "AppDelegate.h"
#import "NAAccount.h"
#import "PathHelper.h"


@implementation DigitAlbumLargeImageViewController
@synthesize smallImgArray;
@synthesize largeImgArray;
@synthesize nextPage;
@synthesize imageId;
@synthesize index;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.hidesBackButton = NO;
    NSString *filePath = [[PathHelper documentDirectoryPathWithName:@"Acc"] 
                          stringByAppendingPathComponent:@"accounts.info"];
    
    NAAccount *acc = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    [self.engine digitAlbumLargeImageWithID:@"4"];
    
    index = 0;
}

-(void)initView{

    largeScrollView.delegate = self;
    smallScrollView.delegate = self;
    
	smallImgArray = [[NSMutableArray alloc] initWithCapacity:[imageArray count]];
    [largeScrollView setFrame:CGRectMake(0, 35, 320, 240)];
    [smallScrollView setFrame:CGRectMake(0, 275, 320, 90)];
    CGSize size = largeScrollView.frame.size;
	for (int i=0; i < [imageArray count]; i++) {
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(size.width * i, 0, 320, 240)];
        [iv setImage:[imageArray objectAtIndex:i]];
        [largeScrollView addSubview:iv];
        iv = nil;
    }
	[largeScrollView setContentSize:CGSizeMake(size.width * [imageArray count], size.height)];
	
	largeScrollView.pagingEnabled = YES;
    largeScrollView.showsHorizontalScrollIndicator = NO;
	
	CGSize size2 = smallScrollView.frame.size;
	for (int i=0; i<[imageArray count]; i++) {
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(100*i + 5*i,10,100,75)];
        [iv setImage:[imageArray objectAtIndex:i]];
		[smallScrollView addSubview:iv];
        [smallImgArray addObject:iv];
        iv = nil;
    }
    [smallScrollView setContentSize:CGSizeMake(100 * [imageArray count] + 60, 80)];
	
    selectFrame = [[NAImageSelectFrameView alloc] initWithFrame:((UIImageView*)[smallImgArray objectAtIndex:index]).frame];
	[smallScrollView addSubview:selectFrame];
    
    CGRect frame = largeScrollView.frame;
    frame.origin.x = frame.size.width * index;
    frame.origin.y = 0;
    [largeScrollView scrollRectToVisible:frame animated:NO];
    
    selectFrame.frame = ((UIImageView*)[smallImgArray objectAtIndex:index]).frame;
    [selectFrame setAlpha:0];
    [UIView animateWithDuration:0.2f animations:^(void){
        [selectFrame setAlpha:0.2f];
    }];
	[smallScrollView setContentOffset:CGPointMake(selectFrame.frame.origin.x, 0) animated:YES];
    NSLog(@"small image touch index %d",index);  
	
	//self.klpScrollView2.pagingEnabled = YES;
    smallScrollView.showsHorizontalScrollIndicator = NO;
	// Do any additional setup after loading the view, typically from a nib.
	
	
	UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singleTap setNumberOfTapsRequired:1];
    
    [largeScrollView addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *smallImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
    [smallImageTap setNumberOfTapsRequired:1];
    [smallScrollView addGestureRecognizer:smallImageTap];

}



#pragma mark -
#pragma mark - Override methods

- (void) requestDidFinished:(RequestEngine *)reqEngine withObject:(id)object {
    
    if ([object isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *) object;
        [dict retain];
        
        NSString *title = [dict objectForKey:kTopTitle];
        if (title != nil && title.length > 0)
            self.titleLabel.text = title;
        
        NSArray *imgDataArray = [dict objectForKey:kData];
        imageArray = [[NSMutableArray alloc] initWithCapacity:0];
        int n = 0;
        for (NSDictionary *dic in imgDataArray) {
            NAImage *naImage = [[NAImage alloc] initWithDictionary:dic];
            NSData* data = [NSData dataWithContentsOfURL:naImage.largeImageURL];
            UIImage *image = [[UIImage alloc] initWithData:data];
            [imageArray addObject:image];
            
            if ([naImage.ID isEqualToString:imageId]) {
                index = n;
            }else {
                n++;
            }
            [naImage release];
        }
        
        [self initView];
        [dict release];
        
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark-- UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{\
	//NSLog(@"scrollViewDidScroll");
	if (scrollView == largeScrollView) {
		CGFloat pageWidth = scrollView.frame.size.width;
		int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
		index = page;
	}else {
		
	}
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //	NSLog(@"scrollViewWillBeginDragging");
	if (scrollView == largeScrollView) {
		
	}else {
		
	}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
	//NSLog(@"scrollViewDidEndDecelerating");
	if (scrollView == largeScrollView) {
		selectFrame.frame = ((UIImageView*)[smallImgArray objectAtIndex:index]).frame;
		[selectFrame setAlpha:0];
		[UIView animateWithDuration:0.2f animations:^(void){
			[selectFrame setAlpha:0.2f];
		}];
		[smallScrollView setContentOffset:CGPointMake(selectFrame.frame.origin.x, 0) animated:YES];
	}else {
		
	}
}

#pragma mark 手势
- (void) handleSingleTap:(UITapGestureRecognizer *) gestureRecognizer{
	CGFloat pageWith = 320;
    
    CGPoint loc = [gestureRecognizer locationInView:largeScrollView];
    NSInteger touchIndex = floor(loc.x / pageWith) ;
    if (touchIndex > [imageArray count]) {
        return;
    }
    NSLog(@"touch index %d",touchIndex);  
}
- (void) handleImageTap:(UITapGestureRecognizer *) gestureRecognizer{
	CGFloat rowHeight = 70;
    CGFloat columeWith = 100;
    CGFloat gap = 5;
    
    CGPoint loc = [gestureRecognizer locationInView:smallScrollView];
    NSInteger touchIndex = floor(loc.x / (columeWith + gap)) + 3 * floor(loc.y / (rowHeight + gap)) ;
    if (touchIndex > [imageArray count]) {
        return;
    }
    index = touchIndex;
    CGRect frame = largeScrollView.frame;
    frame.origin.x = frame.size.width * touchIndex;
    frame.origin.y = 0;
    [largeScrollView scrollRectToVisible:frame animated:NO];
    
    selectFrame.frame = ((UIImageView*)[smallImgArray objectAtIndex:index]).frame;
    [selectFrame setAlpha:0];
    [UIView animateWithDuration:0.2f animations:^(void){
        [selectFrame setAlpha:0.2f];
    }];
	[smallScrollView setContentOffset:CGPointMake(selectFrame.frame.origin.x, 0) animated:YES];
    NSLog(@"small image touch index %d",touchIndex);  
}


@end
